<?php
/**
 * Created by PhpStorm.
 * User: u
 * Date: 2019/4/10
 * Time: 16:25
 */

namespace common\logics\kq;

use Yii;
use yii\base\BaseObject;
use common\services\kq\KqPayService;
use common\widgets\Tool;

class KqPayLogic extends BaseObject implements IKqPay
{
    /** @var \common\sources\read\buyuser\BuyUserAccess $RBuyUserAccess ***/
    private $RBuyUserAccess;
    /** @var \common\sources\read\buyrechargerecord\BuyRechargeRecordAccess  $RBuyRechargeRecordAccess **/
    private $RBuyRechargeRecordAccess;
    /** @var \common\sources\write\buyrechargerecord\BuyRechargeRecordAccess  $WBuyRechargeRecordAccess **/
    private $WBuyRechargeRecordAccess;
    /** @var \common\sources\read\buyuser\BuyUserAcountAccess $RBuyUserAcountAccess  **/
    private $RBuyUserAcountAccess;
    /** @var \common\sources\write\buyuser\BuyUserAcountAccess $WBuyUserAcountAccess **/
    private $WBuyUserAcountAccess;
    /** @var \common\sources\read\pepperrecord\PepperRecordAccess $RPepperRecordAccess **/
    private $RPepperRecordAccess;
    /** @var \common\sources\write\pepperrecord\PepperRecordAccess $WPepperRecordAccess ***/
    private $WPepperRecordAccess;

    public function init()
    {
        $this->RBuyUserAccess = Yii::$container->get("RBuyUserAccess");
        $this->RBuyRechargeRecordAccess = Yii::$container->get("RBuyRechargeRecordAccess");
        $this->WBuyRechargeRecordAccess = Yii::$container->get("WBuyRechargeRecordAccess");
        $this->RBuyUserAcountAccess = Yii::$container->get("RBuyUserAcountAccess");
        $this->WBuyUserAcountAccess = Yii::$container->get("WBuyUserAcountAccess");
        $this->RPepperRecordAccess = Yii::$container->get("RPepperRecordAccess");
        $this->WPepperRecordAccess = Yii::$container->get("WPepperRecordAccess");
        parent::init(); // TODO: Change the autogenerated stub
    }

    public function payAmount($data)
    {
        if(empty($data['buy_id'])){
            return Tool::returnJson([],401,"商家用户id不能为空");
        }
        if(empty($data['pay_type'])){
            return Tool::returnJson([],402,"充值方式不能为空");
        }
        if(empty($data['order_amount'])){
            return Tool::returnJson([],403,"充值金额不能为空");
        }
        if(!($data['pay_type'] == 1 || $data['pay_type'] == 2 )){
            return Tool::returnJson([],405,"选择充值方式有误");
        }
        $kqPayService = new KqPayService();
        $arr = $kqPayService->pay($data);
        if(empty($arr['pay_url'])){
            return Tool::returnJson([],407,"第三方支付异常，请切换其他支付方式");
        }
        //增加充值记录
        return Tool::returnJson($arr,200,"成功");
    }

    //银行卡业务处理
    public function payBank($data)
    {
        if(empty($data['buy_id'])){
            return Tool::returnJson([],401,"商家用户id不能为空");
        }
        if(empty($data['pay_type'])){
            return Tool::returnJson([],402,"充值方式不能为空");
        }
        if(empty($data['order_amount'])){
            return Tool::returnJson([],403,"充值金额不能为空");
        }
        if($data['pay_type'] != 3){
            return Tool::returnJson([],405,"选择充值方式有误");
        }
        if(empty($data['orderId']))
        {
            return Tool::returnJson([],406,"订单编号不能为空");
        }

        $kqPayService = new KqPayService();
        $arr = $kqPayService->payBank($data);
        return $arr;
    }
    //回调处理
    public function doNotify($data)
    {
        $kqPayService = new KqPayService();
        $result = $kqPayService->doNotify($data);
        $rechar_str = '';
        if($_REQUEST['ext2'] == 1)
        {
            $rechar_str = '快钱-微信';
        }else if($_REQUEST['ext2'] == 2)
        {
            $rechar_str = '快钱-支付宝';
        }else if($_REQUEST['ext2'] == 3)
        {
            $rechar_str = '快钱-网银';
        }

        if($result['rtnOK'] == 1)
        {
            $transaction = Yii::$app->db->beginTransaction();
            try{
                $buy_recharge_recode = $this->RBuyRechargeRecordAccess->getBuyRechargeRecord($_REQUEST['orderId']);
                if(empty($buy_recharge_recode))
                {
                    //回调成功之后的判断
                    $trr = [
                        'buy_id' => $_REQUEST['ext1'],
                        'pay_type' => $_REQUEST['ext2'],
                        'amount' => number_format($_REQUEST['payAmount']/100,2,'.',''),
                        'order_id' => $_REQUEST['orderId'],
                        'rech_type' => 2,
                        'pay_status' =>2,
                        'remark' => "充值金额 +".number_format($_REQUEST['payAmount']/100,2,'.',''),
                    ];
                    $res = $this->WBuyRechargeRecordAccess->addBuyRechargeRecord($trr);
                    if($res)
                    {
                        //修改账号余额 买手充值花椒
                        $userAccount = $this->RBuyUserAcountAccess->getBuyUserAccount($_REQUEST['ext1']);
                        if(!empty($userAccount))
                        {
                            $remail_golds = number_format($userAccount['remail_golds']+$_REQUEST['payAmount']/100,2,".","");
                            $this->WBuyUserAcountAccess->modifyBuyUserAccount(['remail_golds' => $remail_golds,"buy_id"=>$_REQUEST['ext1']]);
                        }else
                        {
                            $remail_golds= number_format($_REQUEST['payAmount']/100,2,".","");
                            $this->WBuyUserAcountAccess->addUserAccount(["buy_id"=>$_REQUEST['ext1'],'remail_golds' => $remail_golds,'remain_funds'=>0,'freezing_funds'=>0,'freezing_golds'=>0,'income_golds'=>0]);
                        }
                        $balance = number_format(isset($userAccount['remail_golds']) ? $userAccount['remail_golds']: 0  + $_REQUEST['payAmount']/100,2,".","");
                        //添加充值记录  充值花椒记录
                        $frr = [
                            'buy_id' => $_REQUEST['ext1'],
                            'income' => number_format($_REQUEST['payAmount']/100,2,'.',''),
                            'expend' => '0',
                            'balance' => $balance,
                            'tran_num' => $_REQUEST['orderId'],
                            'remark' => '买手充值花椒',
                            'operator' => "system",
                        ];
                        $str_pepper = $this->WPepperRecordAccess->addPepperRecord($frr);
                        if($str_pepper)
                        {
                            $transaction->commit();
                        }
                    }
                }
            }catch (\Exception $e)
            {
                $transaction->rollBack();
                return Tool::returnJson([],5000,"充值异常");
            }
        }
        return $result['str'];
    }

    //检查是否支付成功
    public function checktOrderStatus($data)
    {
        if(empty($data['bus_id'])){
            return Tool::returnJson([],401,"商家用户id不能为空");
        }
        if(empty($data['orderId']))
        {
            return Tool::returnJson([],402,"商户订单编号不能为空");
        }
        if(empty($data['safetyCode']))
        {
            return Tool::returnJson([],403,"安全码不能为空");
        }
        if($data['safetyCode'] != md5($data['bus_id'].$data['orderId']))
        {
            return Tool::returnJson([],405,"安全码不正确");
        }
        //判断用户是否存在
        $user = $this->RBuyUserAccess->getBuyUserInfo($data['bus_id']);
        if(empty($user))
        {
            return Tool::returnJson([],5150,"用户不存在");
        }
        $rechargerecord = $this->RBusinessRechargeRecordAccess->getRechargeRecord(["order_id" => $data['orderId']]);
        if(empty($rechargerecord))
        {
            return Tool::returnJson([],405,"暂未找到对应的商户");
        }
        return Tool::returnJson($rechargerecord,200,"成功");
    }

    private function request_by_curl($remote_server, $post_string)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $remote_server);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array ('Content-Type: application/json;charset=utf-8'));
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        // 线下环境不用开启curl证书验证, 未调通情况可尝试添加该代码
        curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
        $data = curl_exec($ch);
        curl_close($ch);

        return $data;
    }

}